<script setup>
import productApi from '@/api/product/product.js'
import {ref, reactive, onMounted} from "vue";
import { ElMessage ,ElMessageBox} from 'element-plus'
import categoryApi from '@/api/product/category.js'
import {
  Delete,
  Edit,
} from '@element-plus/icons-vue'
//import product from "@/api/product.js";

//搜索
const productQuery = reactive({
  name:'',
  category1Id: '',
  category2Id: '',
  category3Id: '',
  page:1,
  limit:10
})
//searchCategoryIdList的结构是怎么样的，存的是id?还是什么?
const searchCategoryIdList = ref([])
//这个是用来做什么的
const searchCategoryProps = ref({
  value: 'id',
  label: 'name',
  checkStrictly: true,
  lazy: true,
  lazyLoad(node, resolve) {
    //typeof是什么意思
    if (typeof node.value == 'undefined'){
        node.value = 0;
    }
    categoryApi.selectByParentId(node.value).then(result => {
      if (result.code == 0){
        //为什么要用大括号
        const {data} = result
        data.forEach(item => {
          item.leaf = !item.hasChildren
        })
        resolve(result.data)
      }
    })
  }
})

//分页
const list = ref([])
const total = ref(0)

// 使用 onMounted 生命周期钩子获取数据
/*onMounted(async () => {
  const res = await productApi.list(productQuery);
  list.value = res.data.list; // 更新 list
  total.value = res.data.total; // 假设 total 在响应中也有
});*/
loadData()
function loadData(){
  productApi.list(productQuery).then(result =>{
    console.log(result)
    list.value = result.data.records
    console.log(list.value)
    total.value = result.data.total
    //表格中轮播图处理
    list.value.forEach((item) => {
      if (item.carouselImage){
        item.carouselImageList = item.carouselImage.split(',')
      }
    })
  })
}
const onSearch=()=>{
  productQuery.category1Id=''
  productQuery.category2Id=''
  productQuery.category3Id=''
  if (searchCategoryIdList.value != undefined) {
    if (searchCategoryIdList.value.length == 1) {
      productQuery.category1Id = searchCategoryIdList.value[0]
    } else if (searchCategoryIdList.value.length == 2) {
      productQuery.category1Id = searchCategoryIdList.value[0]
      productQuery.category2Id = searchCategoryIdList.value[1]
    } else if (searchCategoryIdList.value.length == 3) {
      productQuery.category1Id = searchCategoryIdList.value[0]
      productQuery.category2Id = searchCategoryIdList.value[1]
      productQuery.category3Id = searchCategoryIdList.value[2]
    }
  }
  productQuery.page = 1
  loadData()
}

//delete
function deleteById(id){
  ElMessageBox.confirm(
      'proxy will permanently delete the data. Continue?',
      'Warning',
      {
        confirmButtonText: 'OK',
        cancelButtonText: 'Cancel',
        type: 'warning',
      }
  )
      .then(() => {
        productApi.delete(id).then(result =>{
          if (result.code === 0){
            ElMessage({
              message: 'Congrats, this is a success message.',
              type: 'success',
            })
          }//if
        })//productApi
      })
      .catch(() => {
        ElMessage({
          type: 'info',
          message: 'Delete canceled',
        })
      })

  loadData()
}
//deleteAll
const ids = ref([])
function handSelectionChange(rows){
  ids.value = rows.map(row => row.id)
  console.log(ids.value)
}
function deleteAll(){

  ElMessageBox.confirm(
      'proxy will permanently delete the data. Continue?',
      'Warning',
      {
        confirmButtonText: 'OK',
        cancelButtonText: 'Cancel',
        type: 'warning',
      }
  )
      .then(()=>{
        productApi.deleteAll(ids.value).then(result =>{
          if (result.code === 0){
            ElMessage({
              message: 'Congrats, this is a success message.',
              type: 'success',
            })
          }//if
          loadData()
        })
      })

}

//add or update
const dialogFormVisible = ref(false);
//product中存的是根据id查找出来的数值
const product = ref({})
const title = ref()
//添加、编辑弹出框保存选择分类的id
const categoryIdList = ref([])
const categoryProps = ref({
  value: 'id',
  label: 'name',
  lazy: true,
  lazyLoad(node, resolve) {
    //typeof是什么意思
    if (typeof node.value == 'undefined'){
      node.value = 0;
    }
    categoryApi.selectByParentId(node.value).then(result => {
      if (result.code == 0){
        //为什么要用大括号
        const {data} = result
        data.forEach(item => {
          item.leaf = !item.hasChildren
        })
        resolve(result.data)
      }
    })
  }
})
const categoryChange = () =>{
  product.value.category1Id = categoryIdList.value[0]
  product.value.category2Id = categoryIdList.value[1]
  product.value.category3Id = categoryIdList.value[2]
}
//添加轮播图
const carouselImages = ref([])
const fileList = ref([])
//打开添加对话框
function showAddDialog(){
  dialogFormVisible.value = true
  title.value = 'add'
  product.value = {}
  categoryIdList.value = []
  fileList.value=[]
}
//编辑对话框
function showUpdateDialog(id) {
  dialogFormVisible.value = true
  total.value = 'update'
  product.value = {}
  categoryIdList.value = []
  fileList.value=[]
  productApi.getById(id).then(result =>{
    product.value = result.data
    console.log(product.value.carouselImage)
    //回显分类
    categoryIdList.value[0] = product.value.category1Id;
    categoryIdList.value[1] = product.value.category2Id;
    categoryIdList.value[2] = product.value.category3Id;
    //回显轮播图再倒着来一遍就行了
    const carouselImages = product.value.carouselImage.split(',')
    carouselImages.forEach(image => {
      fileList.value.push({url:image});
    })
  })
}

//添加或编辑
function addOrUpdate(){
  //update
  //解决新加入图片和老图片显示格式不一样的问题
  const carouselImage = ref([])
  //这个fileList绑定的是轮播图的值，是一个集合
  fileList.value.forEach(item => {
    if (item.response){
      carouselImage.value.push(item.response.data)
    }else {
      carouselImage.value.push(item.url)
    }
  })
  //用逗号分隔
  product.value.carouselImage = carouselImage.value.join(',')

  if (product.value.id != null){
    productApi.update(product.value).then(result =>{
      if (result.code === 0){
        ElMessage({message:"Congrats, this is a success message",type:"success"})
        dialogFormVisible.value=false
      }//if
      else {
        ElMessage({message:"oops, it didn't work",type:"error"})
      }

      loadData()
    })
  }
  //add
  else {
    //先把轮播图的集合变成数组

    fileList.value.forEach(item => {
      carouselImages.value.push(item.response.data)
    })
    product.value.carouselImage = carouselImages.value.join(',')
    productApi.add(product.value).then(result =>{
      if (result.code === 0){
        ElMessage({message:"Congrats, this is a success message",type:"success"})
      }//if
      else {
        ElMessage({message:"oops, it didn't work",type:"error"})
      }
      dialogFormVisible.value=false
      loadData()
    })
  }
}

//upload
//function handleAvatarSuccess()是返回值函数,已经调用完后端的/upload了
import { Plus } from '@element-plus/icons-vue'
function handleAvatarSuccess(result){
  product.value.image = result.data
}
import {useTokenStore} from "@/store/token.js";
import {id} from "element-plus/es/locale/index";
const tokenStore = useTokenStore()
const headers = ref({
  //携带token传递到后端
  Authorization: tokenStore.token
})
//修改status
/*function handleSwitchChange(row){
  productApi.updateStatus(row).then(result=>{
    if (result.code == 0){
      ElMessage.success(result.msg)
    }else {
      ElMessage({message:"更新失败",type:"error"})
    }
  })
}*/
//修改status状态
const handleSwitchChange = (row) => {
  productApi.updateStatus(row).then(result => {
    if (result.code == 0) {
      ElMessage.success(result.msg)
    } else {
      ElMessage.error(result.msg)
    }
  })
}
</script>

<template>
  <el-card>
    <template #header>
      <!--  两个按钮，添加和批量删除-->
      <el-button type="primary" plain @click="showAddDialog ">添加</el-button>
      <el-button type="primary" plain @click="deleteAll">批量删除</el-button>
    </template>
    <!--  搜索-->

    <el-form :inline="true">
      <el-form-item label="名字" >
        <el-input  v-model="productQuery.name" placeholder="请输入名字" clearable style="width: 180px"/>
      </el-form-item>
      <el-form-item label="分类" >
        <el-cascader
            clearable
            :props="searchCategoryProps"
            v-model="searchCategoryIdList" />
      </el-form-item>
      <el-form-item label="更新时间" >
        <el-date-picker
            v-model="productQuery.beginUpdateTime"
            type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="开始时间"
        />
        <el-date-picker
            v-model="productQuery.endUpdateTime"
            type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="结束时间"
        />
      </el-form-item>
      <el-form-item >
        <el-button type="primary" @click="onSearch">搜索</el-button>
      </el-form-item>
    </el-form>
    <!--  表格-->
    <el-table :data="list" style="width: 100%" ref="multipleTableRef" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55"/>
      <el-table-column fixed prop="id" label="ID"/>
      <el-table-column prop="name" label="名字"/>
      <el-table-column prop="category1Name" label="一级分类"/>
      <el-table-column prop="category2Name" label="二级分类"/>
      <el-table-column prop="category3Name" label="三级分类"/>
      <el-table-column prop="image" label="主图">
        <template #default="scope">
          <img :src="scope.row.image" style="max-height: 40px; max-width: 120px;"/>
        </template>
      </el-table-column>

      <el-table-column prop="image" label="轮播图">
        <template #default="scope">
          <div style="display: flex">
            <img v-for="(image, index) in scope.row.carouselImageList"
                 :key="index"
                 :src="image"
                 style="max-height: 40px; max-width: 120px; margin-right: 5px;" />
          </div>
        </template>
      </el-table-column>

      <el-table-column prop="status" label="状态">
        <template #default="scope">
          <el-switch
              v-model="scope.row.status"
              style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
              :active-value="1"
              :inactive-value="0"
              @change="handleSwitchChange(scope.row)"
          />
        </template>
      </el-table-column>
      <el-table-column prop="updateTime" label="更新时间"/>
      <el-table-column fixed="right" label="Operations">
        <template #default="{ row }">
          <el-button type="primary" :icon="Edit" circle @click="showUpdateDialog(row.id)"/>
          <el-button type="danger" :icon="Delete" circle @click="deleteById(row.id)"/>
        </template>
      </el-table-column>
    </el-table>
    <div class="demo-pagination-block" style="margin-top: 20px">

      <el-pagination
          v-model:current-page="productQuery.page"
          v-model:page-size="productQuery.limit"
          :page-sizes="[10, 20, 30, 40]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @change="loadData"
      />
    </div>

    <!--  add or update-->
    <!--添加、编辑弹出框-->
    <el-dialog v-model="dialogFormVisible" :title="title" width="500" :lock-scroll="false">
      <el-form :model="product">
        <el-form-item label="名字" :label-width="60">
          <el-input v-model="product.name" autocomplete="off"/>
        </el-form-item>
        <el-form-item label="分类" :label-width="60">
          <el-cascader
              v-model="categoryIdList"
              :props="categoryProps"
              @change="categoryChange"
              style="width: 100%" />
        </el-form-item>
        <el-form-item label="图片" :label-width="60">
          <el-upload
              class="avatar-uploader"
              action="/api/product/upload"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :headers="headers"
          >
            <img v-if="product.image" :src="product.image" class="avatar"/>
            <el-icon v-else class="avatar-uploader-icon">
              <Plus/>
            </el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="轮播图" :label-width="60">
        <el-upload
            v-model:file-list="fileList"
            action="/api/product/upload"
            list-type="picture-card"
        >
          <el-icon><Plus /></el-icon>
        </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="addOrUpdate">
            确认
          </el-button>
        </div>
      </template>
    </el-dialog>
  </el-card>
</template>

<style scoped>



.demo-date-picker {
  display: flex;
  width: 100%;
  padding: 0;
  flex-wrap: wrap;
}
.demo-date-picker .block {
  padding: 30px 0;
  text-align: center;
  border-right: solid 1px var(--el-border-color);
  flex: 1;
}
.demo-date-picker .block:last-child {
  border-right: none;
}
.demo-date-picker .demonstration {
  display: block;
  color: var(--el-text-color-secondary);
  font-size: 14px;
  margin-bottom: 20px;
}
</style>
<style>
.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}
</style>